package com.yungu.swift.assets.driver.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.yungu.swift.assets.driver.dao.CarMapper;
import com.yungu.swift.assets.driver.dao.DriverCheckMapper;
import com.yungu.swift.assets.driver.dao.DriverMapper;
import com.yungu.swift.assets.driver.model.dto.CarDto;
import com.yungu.swift.assets.driver.model.dto.DriverCheckDto;
import com.yungu.swift.assets.driver.model.dto.DriverDto;
import com.yungu.swift.assets.driver.model.param.AdminDriverCheckPassParam;
import com.yungu.swift.assets.driver.model.param.AdminDriverCheckRejectParam;
import com.yungu.swift.assets.driver.service.CarService;
import com.yungu.swift.assets.driver.service.DriverCheckService;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.assets.utils.DriverUniqueIdUtils;
import com.yungu.swift.assets.utils.SendMessageUtils;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.model.admin.AdminParam;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.common.service.CommonSmsService;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.DriverConstant;
import com.yungu.swift.system.marketing.model.dto.MarketingChannelLogDto;
import com.yungu.swift.system.marketing.model.dto.MarketingInviteLogDto;
import com.yungu.swift.system.marketing.service.MarketingChannelLogService;
import com.yungu.swift.system.marketing.service.MarketingChannelService;
import com.yungu.swift.system.marketing.service.MarketingGiftService;
import com.yungu.swift.system.marketing.service.MarketingInviteLogService;
import com.yungu.swift.system.sys.model.dto.SysAccountDriverDto;
import com.yungu.swift.system.sys.model.dto.SysBusinessOperateLogDto;
import com.yungu.swift.system.sys.model.enums.SysBusinessOperateEnum;
import com.yungu.swift.system.sys.service.SysAccountDriverService;
import com.yungu.swift.system.sys.service.SysBusinessOperateLogService;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.Md5Utils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 司机申请业务逻辑接口实现类
 *
 * @author cuixiuyin - Generate
 * @version 1.1.1-SNAPSHOT
 * @since 2018-07-05 17:57
 */
@Slf4j
@Service
public class DriverCheckServiceImpl extends BaseServiceImpl<DriverCheckDto> implements DriverCheckService {
    @Autowired
    private DriverCheckMapper driverCheckMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CarService carService;
    @Autowired
    private DriverService driverService;

    @Reference
    private CommonSmsService commonSmsService;
    @Reference
    private MarketingInviteLogService marketingInviteLogService;
    @Reference
    private MarketingGiftService marketingGiftService;
    @Reference
    private MarketingChannelService marketingChannelService;
    @Reference
    private MarketingChannelLogService marketingChannelLogService;
    @Reference
    private SysAccountDriverService sysAccountDriverService;
    @Reference
    private SysBusinessOperateLogService sysBusinessOperateLogService;

    @Override
    protected IMapper<DriverCheckDto> getMapper() {
        return driverCheckMapper;
    }

    @Override
    @Transactional
    public ResponseData<Boolean> pass(AdminDriverCheckPassParam checkPassParam) {
        try {
            DriverDto driverDto = new DriverDto();
            List<DriverCheckDto> list = driverCheckMapper.list(MapUtils.build("uuid", checkPassParam.getUuid()));
            if (CollectionUtils.isNotEmpty(list)) {
                DriverCheckDto checkDto = list.get(0);
                Map<String, Object> params = MapUtils.build(4);
                //检验手机号
                params.put("mobile", checkDto.getMobile());
                params.put("idCard", checkDto.getIdCard());
                params.put("appid", checkDto.getAppid());
                ResponseData<List<DriverDto>> validDriver = driverService.getValidDriver(params);
                if (validDriver.isSuccess() && CollectionUtils.isNotEmpty(validDriver.getData())) {
                    return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "该司机手机号或身份证号已经注册了");
                }

                //校验车辆 - 存在就绑定，不存在则不处理
                if (StringUtils.isNotEmpty(checkPassParam.getPlateNum())) {
                    ResponseData<CarDto> responseData = carService.get(MapUtils.build("plateNum", checkPassParam.getPlateNum()));
                    if (responseData.isSuccess() && responseData.getData() != null) {
                        driverDto.setCarUuid(responseData.getData().getUuid());
                    }
                }
                BeanUtils.copyProperties(checkDto, driverDto);
                driverDto.setUuid(StringUtils.buildUUID());
                driverDto.setDriverNo(checkPassParam.getDriverNo());
                driverDto.setCreateBy(checkPassParam.getUserUuid());
                driverDto.setCreateOn(new Date());
                driverDto.setDriverCheckUuid(checkPassParam.getUuid());
                driverDto.setLicenseId(checkDto.getLicenseNum());
                driverDto.setDriverIdCardImg(checkDto.getFullDriverIdCardImg());
                driverDto.setNetworkCarCertificationImg(checkDto.getNetworkCarCertificationImg());
                // 出租车业务代理和公司不由后台选择
                if (CommonConstant.BUSINESS_TYPE_TAXI != checkPassParam.getBusinessType()) {
                    driverDto.setAgentUuid(checkPassParam.getAgentUuid());
                    driverDto.setCompanyUuid(checkPassParam.getCompanyUuid());
                }
                driverDto.setCityUuid(checkPassParam.getCityUuid());
                //国籍 "156" —— 默认中国
                driverDto.setDriverNationality("156");
                //全职司机
                driverDto.setFullTimeDriver(1);
                //初始密码
                driverDto.setPassword(Md5Utils.encode("123456"));
                //完成订单数
                driverDto.setOrderCount(new Integer(0));
                //1 ：下班
                driverDto.setIsWork(DriverConstant.DRIVER_IS_NOT_WORK);
                // 1: 正常
                driverDto.setStatus(DriverConstant.DRIVER_STATUS_NORMAL);
                // 1 :首次登录
                driverDto.setIsFirst(DriverConstant.IS_FIRST);
                //余额
                driverDto.setBalance(new Double(0));
                //推送级别
                driverDto.setPushLevel(1);
                //1：全部
                driverDto.setRemindType(DriverConstant.DRIVER_REMIND_TYPE_ALL);
                // 设置唯一编号
                driverDto.setDriverUniqueId(DriverUniqueIdUtils.getDriverUniqueId(driverDto.getCityUuid()));
                // 设置未激活状态
                driverDto.setActive(0);

                // 记录优惠券渠道
                Map<String, Object> build = MapUtils.build(4);
                build.put("invitee", checkDto.getMobile());
                // 被邀请作为司机
                build.put("inviteeType", 2);
                // 被司机邀请
                build.put("inviterType", 2);
                ResponseData<MarketingInviteLogDto> resData = marketingInviteLogService.get(build);
                // 判断司机是否被邀请进入的 如果是被邀请进入的司机 则需要给邀请人礼包奖励
                if (resData.isSuccess() && resData.getData() != null) {
                    MarketingInviteLogDto inviteLogDto = resData.getData();
                    // 给邀请人现金返现
                    marketingGiftService.drawDriverInviteDriverGift(inviteLogDto.getInviter(), inviteLogDto.getUuid());
                    // 获取司机邀请司机渠道id
                    ResponseData<String> findChannelUuidByConditions = marketingChannelService.findChannelUuidByConditions(
                            MapUtils.build("type", 4));
                    driverDto.setChannelUuid(findChannelUuidByConditions.getData());
                    if (StringUtils.isNotEmpty(findChannelUuidByConditions.getData())) {
                        // 记录渠道邀请日志
                        MarketingChannelLogDto marketingChannelLogDto = new MarketingChannelLogDto();
                        marketingChannelLogDto.setUuid(StringUtils.buildUUID());
                        marketingChannelLogDto.setChannelUuid(findChannelUuidByConditions.getData());
                        marketingChannelLogDto.setUserUuid(driverDto.getUuid());
                        marketingChannelLogDto.setAppid(driverDto.getAppid());
                        marketingChannelLogDto.setAgentUuid(driverDto.getAgentUuid());
                        marketingChannelLogDto.setCompanyUuid(driverDto.getCompanyUuid());
                        marketingChannelLogDto.setCreateBy(driverDto.getCreateBy());
                        marketingChannelLogDto.setCreateOn(new Date());
                        // 新用户
                        marketingChannelLogDto.setNewUser(1);
                        marketingChannelLogService.add(marketingChannelLogDto);
                    }
                }
                //是否带车注册 0否 1是
                if(checkDto.getHaveCar()==1){
                    CarDto carDto = new CarDto();
                    BeanUtils.copyProperties(checkDto,carDto);
                    carDto.setUuid(StringUtils.buildUUID());
                    carDto.setCreateBy(checkPassParam.getUserUuid());
                    carDto.setCreateOn(new Date());
                    carDto.setDrivingLicenseImg(checkDto.getDrivingPic());
                    carDto.setDrivingLicenseSubImg(checkDto.getDrivingPicBack());
                    carMapper.add(carDto);
                    driverDto.setCarUuid(carDto.getUuid());
                }
                driverMapper.add(driverDto);

                //新增司机账户表
                SysAccountDriverDto accountDriverDto = new SysAccountDriverDto();
                accountDriverDto.setUuid(driverDto.getUuid());
                accountDriverDto.setAppid(driverDto.getAppid());
                accountDriverDto.setAccountName(driverDto.getName());
                accountDriverDto.setFrozenBalance(BigDecimal.ZERO);
                accountDriverDto.setCanFrowardBalance(BigDecimal.ZERO);
                accountDriverDto.setFrowardAccumulate(BigDecimal.ZERO);
                accountDriverDto.setAlipayAccumulate(BigDecimal.ZERO);
                accountDriverDto.setTenpayAccumulate(BigDecimal.ZERO);
                accountDriverDto.setCreateOn(new Date());
                sysAccountDriverService.add(accountDriverDto);

                //更新审核表
                DriverCheckDto updDriverCheckDto = new DriverCheckDto();
                updDriverCheckDto.setUuid(checkDto.getUuid());
                updDriverCheckDto.setRemark(null);
                updDriverCheckDto.setStatus(DriverConstant.DRIVER_CHECK_PASS);
                updDriverCheckDto.setAgentUuid(driverDto.getAgentUuid());
                updDriverCheckDto.setCompanyUuid(driverDto.getCompanyUuid());
                updDriverCheckDto.setPlateNum(driverDto.getCarUuid() != null ? driverDto.getPlateNum() : null);
                updDriverCheckDto.setUpdateBy(checkPassParam.getUserUuid());
                updDriverCheckDto.setUpdateOn(new Date());
                driverCheckMapper.edit(updDriverCheckDto);
                //插入操作日志
                addOperetaLog(checkPassParam,updDriverCheckDto,"",checkDto.getMobile(),checkDto.getName());
                //发送短信
//                SendMessageUtils.driverPassSend(commonSmsService, checkDto, driverDto);
                commonSmsService.sendAliCommon(checkDto.getMobile(),"123456","","2");
                return ResponseData.buildSuccessResponse("审核成功", Boolean.TRUE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "系统异常，审核失败");
    }


    @Override
    public ResponseData<Boolean> reject(AdminDriverCheckRejectParam checkRejectParam) {
        List<DriverCheckDto> list = driverCheckMapper.list(MapUtils.build("uuid", checkRejectParam.getUuid()));
        if (CollectionUtils.isNotEmpty(list)) {
            DriverCheckDto driverCheckDto = list.get(0);
            DriverCheckDto driverCheckParam = new DriverCheckDto();
            driverCheckParam.setUuid(list.get(0).getUuid());
            driverCheckParam.setStatus(DriverConstant.DRIVER_CHECK_NOT_PASS);
            driverCheckParam.setRemark(checkRejectParam.getRemark());
            if (driverCheckMapper.edit(driverCheckParam) > 0) {
//                SendMessageUtils.driverRejectSend(commonSmsService, driverCheckDto, checkRejectParam.getRemark());
                //插入操作日志
                addOperetaLog(checkRejectParam,driverCheckParam,checkRejectParam.getRemark(),driverCheckDto.getMobile(),driverCheckDto.getName());
                //发送短信给用户
                commonSmsService.sendAliCommon(list.get(0).getMobile(),"","","3");
                return ResponseData.buildSuccessResponse("驳回成功", Boolean.TRUE);
            }
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "驳回异常");
    }

    @Override
    public ResponseData<DriverCheckDto> getLatest(Map<String, Object> map) {
        //离职
        map.put("dimission", DriverConstant.DRIVER_STATUS_DIMISSION);
        return ResponseData.buildSuccessResponse(driverCheckMapper.getLatest(map));
    }


    @Override
    public ResponseData<Map<String, Object>> validate(DriverCheckDto dto) {
        Map<String, Object> params = MapUtils.build();
        //检验手机号
        params.put("mobile", dto.getMobile());
        params.put("appid", dto.getAppid());
        ResponseData<List<DriverDto>> ajaxListDri = driverService.getValidDriver(params);
        if (ajaxListDri.isSuccess()) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "该司机手机号已经注册了");
        }
        //检验身份证号
        params.put("appid", dto.getAppid());
        params.put("idCard", dto.getIdCard());
        ajaxListDri = driverService.getValidDriver(params);
        if (ajaxListDri.isSuccess()) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "该司机身份证号已经注册了");
        }
        //检索车辆是否已经注册了
        params.clear();
        params.put("plateNum", dto.getPlateNum());
        ResponseData<CarDto> dtoResponseData = carService.get(params);
        params.clear();
        if (dtoResponseData.isSuccess() && dtoResponseData.getData() != null) {
            CarDto carDto = dtoResponseData.getData();
            //车辆是否与审核信息中的车辆企业信息保持一致
            if (carDto.getCompanyUuid().equals(dto.getCompanyUuid()) == false) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "审核通过失败，该车辆已存在其他企业");
            }
            //检索车辆绑定司机信息
            params.put("uuid", carDto.getUuid());
            ResponseData<List<Map<String, String>>> responseData = carService.getDriInfo(params);
            params.clear();
            List<Map<String, String>> drivers = responseData.getData();
            if (drivers.size() > 0) {
                StringBuilder driversStr = new StringBuilder();
                for (Map<String, String> driver : drivers) {
                    driversStr.append("，" + driver.get("name") + "（" + driver.get("mobile") + "）");
                }
                //删除首个逗号
                driversStr.deleteCharAt(0);
                //resultCode 首位0/1表示车辆是否存在，第二位0/1表示车辆是否有绑定司机
                params.put("resultCode", "11");
                params.put("driversStr", driversStr);
            } else {
                params.put("resultCode", "10");
            }
        } else {
            params.put("resultCode", "0");
        }
        return ResponseData.buildSuccessResponse("", params);
    }

    private void addOperetaLog(AdminParam adminParam, DriverCheckDto driverCheckDto,String remark,String driverMobile,String driverName){
        try{
            SysBusinessOperateLogDto operateLogDto = new SysBusinessOperateLogDto();
            operateLogDto.setBeforeValue("未审核");
            String driverInfo = "("+driverName+"-"+driverMobile+")";
            if(driverCheckDto.getStatus().equals(DriverConstant.DRIVER_CHECK_PASS)){
                operateLogDto.setAfterValue("审核通过"+driverInfo);
                operateLogDto.setOperationCode(SysBusinessOperateEnum.DRIVER_AUDIT_PASS.getCode());
                operateLogDto.setOperationName(SysBusinessOperateEnum.DRIVER_AUDIT_PASS.getName());
            }else{
                operateLogDto.setAfterValue("审核拒绝"+driverInfo);
                operateLogDto.setOperationCode(SysBusinessOperateEnum.DRIVER_AUDIT_REJECT.getCode());
                operateLogDto.setOperationName(SysBusinessOperateEnum.DRIVER_AUDIT_REJECT.getName());
            }

            operateLogDto.setOperationDescribe("客服审核司机注册申请");
            operateLogDto.setCreateBy(adminParam.getUserUuid());
            operateLogDto.setCreateOn(new Date());
            operateLogDto.setAgentUuid(adminParam.getUserAgentUuid());
            operateLogDto.setCompanyUuid(adminParam.getUserCompanyUuid());
            operateLogDto.setAppid(adminParam.getAppid());
            operateLogDto.setUuid(StringUtils.buildUUID());
            operateLogDto.setOperationUserIp(adminParam.getUserip());
            operateLogDto.setRemark(remark);
            sysBusinessOperateLogService.add(operateLogDto);
        }catch (Exception e){

        }
    }
}
